package com.sjf.batch.listen;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpiredListener extends KeyExpirationEventMessageListener {

    @Autowired
    public RedisTemplate<String, String> redisTemplate;

    public RedisKeyExpiredListener ( RedisMessageListenerContainer listenerContainer ) {
        super (listenerContainer);
    }

    /**
     * redis 失效监听
     * 监听key包含的
     *
     * @param message
     * @param bytes
     */
    @Override
    public void onMessage ( Message message , byte[] bytes ) {
        RedisSerializer<?> serializer = redisTemplate.getValueSerializer ();
        String channel = String.valueOf (serializer.deserialize (message.getChannel ()));
        String format = StrUtil.format ("__keyevent@{}__:expired" , "1");
        //获取失效key名称
        String expireKey = String.valueOf (serializer.deserialize (message.getBody ()));
        System.out.println ("获取失效key名称" + expireKey);
        if ( expireKey.contains ("key名称") ) {
            //在这里处理相关的业务

        }
    }
}